﻿using System;
using IQIGame.Onigao.GamePlay;
using LFloatMath.Math;

namespace IQIGame.Onigao.Logic
{
    public class AttributeComponent : TComponent
    {
        public AttributeProperty attr;
        public Unit unit { get; private set; }

        protected override void OnDispose()
        {
        }

        public override void OnCreate(TEntity entity)
        {
            this.unit = entity as Unit;
            this.attr = new AttributeProperty();
        }

        public void Initialize(int[] attrValue)
        {
            this.attr.Initialize(attrValue, this.unit.lv);
            if (this.unit.battle.enterPOD.initAttrbute)
            {
                this.Set(EAttributeType.Hp, this.attr.Get(EAttributeType.MaxHp).ToInt(), EAttributeAddType.Add);
                this.Set(EAttributeType.SP, this.attr.Get(EAttributeType.InitSP).ToInt(), EAttributeAddType.Add);
            }
        }

        public LFloat Get(EAttributeType rType)
        {
            return this.attr.Get(rType);
        }

        public void Set(EAttributeType rType, int nValue, EAttributeAddType rAddType = EAttributeAddType.Base)
        {
            if (this.unit.battle != null)
            {
                var rResultCtrl = this.unit.battle.playCtrl.resultCtrl;
                var rPOD = BattleUpdateFactory.CreateAttrChange(rType, rAddType, nValue, false, this.unit.GUID);
                rResultCtrl.Add(rPOD);
            }

            this.attr.Set(rType, nValue, rAddType);
        }

        public void Add(EAttributeType rType, int nValue, EAttributeAddType rAddType = EAttributeAddType.Add)
        {
            if (this.unit.battle != null)
            {
                var rResultCtrl = this.unit.battle.playCtrl.resultCtrl;
                var rPOD = BattleUpdateFactory.CreateAttrChange(rType, rAddType, nValue, true, this.unit.GUID);
                rResultCtrl.Add(rPOD);
            }
            switch (rAddType)
            {
                case EAttributeAddType.Add:
                    this.attr.Add(rType, nValue);
                    break;
                case EAttributeAddType.Percent:
                    this.attr.AddPercent(rType, nValue);
                    break;
            }
        }

        public int GetPanel(EAttributeType rType)
        {
            return this.attr.GetAll(rType).Item1;
        }

        public void RecoverSP(int nValue)
        {
            var nOld = this.Get(EAttributeType.SP).ToInt();
            var nMaxSp = this.Get(EAttributeType.MaxSP).ToInt();
            var nAfter = Math.Clamp(nOld + nValue, 0, nMaxSp);
            var nRecover = nAfter - nOld;
            this.Add(EAttributeType.SP, nRecover);
        }
    }
}